package mlp.game.applebucking;

import com.overkill.game.GameOptions;
import com.overkill.game.RenderView;
import com.overkill.game.TheGameActivity;
import com.overkill.game.Tools;
import com.playtomic.android.api.Playtomic;
import com.playtomic.android.api.PlaytomicLeaderboards;
import com.playtomic.android.api.PlaytomicRequestListener;
import com.playtomic.android.api.PlaytomicResponse;
import com.playtomic.android.api.PlaytomicScore;
import com.playtomic.android.api.PlaytomicScoreBoardView;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Typeface;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class GameActivity extends TheGameActivity {
	public static final String SETTINGS = "applebucking";
	
	AppleBloomEngine gameEngine;
	int points = 0;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
				
		GameOptions options = new GameOptions();
		options.put("difficulty", getIntent().getExtras().getString("difficulty"));		
		gameEngine = new AppleBloomEngine(options, this, 30);		
		
		inizialize(gameEngine, R.id.gameView);
		
		Log.i("renderView", "isSurfaceCreated:" + renderView.isSurfaceCreated);
		
		((PlaytomicScoreBoardView)findViewById(R.id.listScore)).setScoreTable(options.getString("difficulty", "HARD"));	
		
		Playtomic.Log().playerLevelStart(options.getString("difficulty", "HARD"));	
		

		//((Button)findViewById(R.id.btn_submit)).setEnabled(false);
	}	
	
	@Override
	public void onBackPressed() {
		if (gameEngine.gameRunning) {
			gameEngine.pauseGame();
			new AlertDialog.Builder(this)
					.setIcon(android.R.drawable.ic_dialog_alert)
					.setTitle(R.string.quit_dialog_title)
					.setMessage(R.string.quit_dialog_message)
					.setPositiveButton(android.R.string.yes,
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog, int which) {
									finish();
									Playtomic.Log().playerLevelQuit(gameEngine.getOptions().getString("difficulty", "HARD"));
								}
							}).setNegativeButton(android.R.string.no, null)
					.show();
		} else {
			super.onBackPressed();
		}
	}

	@Override
	public void gameOver(GameOptions options) {
		final int totalApples = options.getInteger("SCORE_TOTAL_APPLES", 0);
		final int caughtApples = options.getInteger("SCORE_CAUGHT_APPLES", 0);
		final int missedApples = options.getInteger("SCORE_MISSED_APPLES", 0);
		
		points = caughtApples - 2 * missedApples;
		
		Playtomic.Log().playerLevelWin(gameEngine.getOptions().getString("difficulty", "HARD"));
		
		DisplayMetrics metrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(metrics);
		final Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.background);
		final RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
														LayoutParams.WRAP_CONTENT,
														LayoutParams.MATCH_PARENT);
		params.setMargins(metrics.widthPixels - b.getWidth(), 0, 0, 0);
		final Typeface celestia = Typeface.createFromAsset(getAssets(),	RenderView.TYPEFACE_PATH);
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				// Force background to be scaled on low dpi devices
				ImageView backgroundImageView = (ImageView) findViewById(R.id.imageGameoverBackground);
				backgroundImageView.setLayoutParams(params);
				// set Values
				TextView scoreText = (TextView) findViewById(R.id.txt_scoreboard);
				scoreText.setText(getString(R.string.final_score, caughtApples, missedApples));
				float missed = (missedApples * 1.0f) / totalApples;
				if (missed < 0.1) {
					scoreText.append(getString(R.string.end_success));
				} else {
					scoreText.append(getString(R.string.end_fail));
				}
				Tools.setTypeFace(GameActivity.this, celestia, R.id.txt_scoreboard, R.id.btn_quit, R.id.btn_restart, R.id.btn_submit);
				// Show Gameover screen
				renderView.setVisibility(View.GONE);
				((RelativeLayout) findViewById(R.id.gameOverLayout)).setVisibility(View.VISIBLE);
				
				// ((Button)findViewById(R.id.btn_submit)).setText("Points: " + points);
			}
		});
	}

	public void onRestartClick(View view) {
		Playtomic.Log().playerLevelRetry(gameEngine.getOptions().getString("difficulty", "HARD"));
		
		Intent i = this.getIntent();
		i.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
		overridePendingTransition(0, 0);
		finish();
		overridePendingTransition(0, 0);
		startActivity(i);
	}

	public void onQuitClick(View view) {
		finish();
	}
	
	public void onSubmitClick(View view){
		requestScoreSubmit(points);	
	}
	
	private void requestScoreSubmit(final int points){
		final SharedPreferences sharedPreferences = getSharedPreferences(SETTINGS, Context.MODE_PRIVATE);
		if(sharedPreferences.getBoolean("submit_score", true) == false)
			return;
		
		AlertDialog.Builder dialog = new AlertDialog.Builder(GameActivity.this);
		final EditText editText = new EditText(this);
		editText.setHint("Enter your name");
		editText.setText(sharedPreferences.getString("last_score_name", ""));
		dialog.setCancelable(false);
		dialog.setView(editText);
		dialog.setTitle("Submit score?");
		dialog.setIcon(android.R.drawable.ic_dialog_info);
		dialog.setMessage("Do you want to submit your score of " + points + " points?");
		dialog.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				String name = editText.getText().toString();
				if(name.length() <= 0){
					Toast.makeText(GameActivity.this, "Please enter a name", Toast.LENGTH_SHORT).show();
					requestScoreSubmit(points);
				} else {
					PlaytomicScore score = new PlaytomicScore(name, points);
					leaderBoardSave(score);
					Editor editor = sharedPreferences.edit();
					editor.putString("last_score_name", name);
					editor.commit();
					dialog.dismiss();
				}								
			}
		});
		dialog.setNegativeButton(android.R.string.no, null);
//		dialog.setNegativeButton("Never", new DialogInterface.OnClickListener() {			
//			@Override
//			public void onClick(DialogInterface dialog, int which) {
//				Editor editor = sharedPreferences.edit();
//				editor.putBoolean("submit_score", false);
//				editor.commit();
//				dialog.dismiss();								
//			}
//		});
		dialog.show();
	}
	
	private void leaderBoardSave(PlaytomicScore score) {
		PlaytomicLeaderboards leaderboards = new PlaytomicLeaderboards();

	    leaderboards.setRequestListener(new PlaytomicRequestListener<PlaytomicScore>() {
	        @Override
			public void onRequestFinished(PlaytomicResponse<PlaytomicScore> playtomicResponse) {
	            if(playtomicResponse.getSuccess()) {
	                // we call a function for successed cases
					Toast.makeText(GameActivity.this, "Your score was submited", Toast.LENGTH_SHORT).show();
					((Button)findViewById(R.id.btn_submit)).setEnabled(false);
					((PlaytomicScoreBoardView)findViewById(R.id.listScore)).reloadData();
	            }            
	            else {
	                // we call a function for failed cases 
	                requestLeaderBoardListFailed(playtomicResponse.getErrorCode(), 
	                                                playtomicResponse.getErrorMessage());
	            }
	        }
	    });    
	    
	    leaderboards.save(gameEngine.getOptions().getString("difficulty", "HARD"), score, true, false);
	    // leaderboards.list(, true, "alltime", 1, 20, null);
	}

//	private void requestLeaderBoardListFinished(final ArrayList<PlaytomicScore> data) {
//	   	runOnUiThread(new Runnable() {			
//			@Override
//			public void run() {
//				((Button)findViewById(R.id.btn_submit)).setEnabled(false);
//				((PlaytomicScoreBoardView)findViewById(R.id.listScore)).setData(data);
//			}
//		});
//	}

	private void requestLeaderBoardListFailed(int errorCode, String message) {
		Toast.makeText(this, "Error submitting score\nError: " + message + " (" + errorCode + ")", Toast.LENGTH_LONG).show();
		((Button)findViewById(R.id.btn_submit)).setEnabled(false);
		Log.i("Leaderboard", "Leaderboard list failed to list because of errorcode #" + errorCode 
	            +  " - Message:" + message);
	}
}

